package com.lin.service.impl;

import com.lin.base.Role;
import com.lin.entity.User;
import com.lin.mapper.UserMapper;
import com.lin.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lin
 * @since 2022-06-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Boolean saveUser(User user) {
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        user.setRole(Role.USER.role);
        return this.save(user);
    }

    @Override
    public User getUser(Integer uid) {
        return this.getById(uid);
    }


    @Override
    @Cacheable(value = "role", key = "#uid")
    public List<GrantedAuthority> getRole(Integer uid) {
        return AuthorityUtils.commaSeparatedStringToAuthorityList(this.getById(uid).getRole());
    }

    @Override
    public Boolean hasRole(Integer uid, Role role) {
        List<GrantedAuthority> authorities = getRole(uid);
        for (GrantedAuthority authority : authorities) {
            if (authority.getAuthority().equals(role.role))
                return true;
        }
        return false;
    }
}
